
package com.chongchong.system.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chongchong.core.boot.file.SysFile;
import com.chongchong.core.mp.base.BaseServiceImpl;
import com.chongchong.core.tool.utils.DateUtil;
import com.chongchong.system.mapper.AttachMapper;
import com.chongchong.system.service.IAttachService;
import com.chongchong.user.entity.Attach;
import com.chongchong.user.vo.AttachVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 附件表 服务实现类
 *
 * @author
 */
@Slf4j
@Service
public class AttachServiceImpl extends BaseServiceImpl<AttachMapper, Attach> implements IAttachService {
    @Value("${file.profile}")
		private String filePath;
    @Value("${file.domainName}")
    private String fileDomainName;

    @Override
    public IPage<AttachVO> selectAttachPage(IPage<AttachVO> page, AttachVO attach) {
        return page.setRecords(baseMapper.selectAttachPage(page, attach));
    }

    @Override
    public Attach upload(MultipartFile file) throws IOException {
        SysFile sysFile = new SysFile();
        sysFile.setFile(file);
        sysFile.setFileName(file.getName());
        sysFile.setOriginalFileName(file.getOriginalFilename());

        return uploadFile(file.getInputStream(), sysFile);
    }

    Attach uploadFile(InputStream inputStream, SysFile sysFile) {
        try {
            String md5 = DigestUtils.md5Hex(inputStream);
			sysFile.setMd5(md5);
        }catch (Exception e){
            e.printStackTrace();
        }
        //判断MD5是否已经存在
        QueryWrapper<Attach> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", sysFile.getMd5());
        Attach attachMd5 = this.getOne(queryWrapper);
        if (attachMd5 != null) {
            return attachMd5;
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String key = DateUtil.formatDate(new Date()) + "/" + uuid + sysFile.getOriginalFileName();
        String uploadPath = filePath + key;
        String originalFileName = sysFile.getOriginalFileName();
        File file = FileUtil.writeFromStream(inputStream, uploadPath);
		sysFile.setUploadPath(uploadPath);
        Attach attach = new Attach();
        attach.setLink("/" + key);
        attach.setName(sysFile.getFileName());
        attach.setAttachSize(file.length());
        attach.setDomain(fileDomainName);
        attach.setExtension(originalFileName.substring(originalFileName.lastIndexOf(".")));
        attach.setOriginalName(originalFileName);
        attach.setSource(sysFile.getSource());
        attach.setSourceId(sysFile.getSourceId());
        attach.setMd5(sysFile.getMd5());
        this.save(attach);
        return attach;
    }

    @Override
    public boolean deleteFiles(@NotEmpty List<Long> ids) {
        // 删除文件
        List<Attach> list = this.listByIds(ids);
        String substring = filePath.substring(0, filePath.lastIndexOf("/"));
        for (Attach attach : list) {
            FileUtil.del(substring + attach.getLink());
        }
        return super.removeByIds(ids);
    }

    /**
     * 下载文件
     *
     * @param response response
     * @param fileId   fileId
     */
    @Override
    public void down(HttpServletResponse response, Long fileId) {
        Attach attach = getById(fileId);
        if (attach != null) {
            Attach entity = new Attach(); //(attach.getId() + "", attach.getName(), attach.getAttachSize(), 0L, "0");
            entity.setId(attach.getId());
            entity.setName(attach.getName());
            entity.setAttachSize(attach.getAttachSize());
            entity.setLink(attach.getLink());

            URL urlTmp;
            try {
                urlTmp = new URL(attach.getLink());
                HttpURLConnection conn = (HttpURLConnection) urlTmp.openConnection();
                //设置超时间为3秒
                conn.setConnectTimeout(3 * 1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                //得到输入流
                InputStream inputStream = conn.getInputStream();

                if (inputStream != null) {
                    final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(attach.getName()), "application/octet-stream");
                    ServletUtil.write(response, inputStream, contentType, attach.getName());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
